from whiff import resolver
from whiff import whiffenv
from whiff.middleware import misc

expectMap = {
    "the" : "article",
    "cat" : "noun",
    "walked" : "verb",
    "slowly" : "adverb"
    }

def badDrop(name, color="red"):
    return """
    (function() {
        var elt = document.getElementById("%s");
        elt.style.backgroundColor = "%s";
    }) ();
    """ % (name, color)

def goodDrop(name):
    return badDrop(name, "green");

def checkMap(mapping):
    its = list(mapping)
    its.sort()
    L = []
    for (name, value) in its:
        if value == expectMap[name]:
            feedback = goodDrop(name)
        else:
            feedback = badDrop(name)
        L.append(feedback)
    return "\n".join(L)

class __middleware__(misc.utility):
    def __call__(self, env, start_response):
        env = resolver.process_cgi(env, parse_cgi=True)
        wordMappingStr = whiffenv.cgiGet(env, "wordMapping", '{"the": "noun"}')
        wordMappingStr = resolver.unquote(wordMappingStr)
        wordMapping = self.param_json(wordMappingStr, env)
        feedbacks = checkMap(wordMapping)
        #pr "sending feedbacks"
        #pr feedbacks
        return self.deliver_page(feedbacks, env, start_response, "application/javascript")


    
